<?php
class Calendar_Model_Reservation {

	/* Status */
	const SUCCESS = 'SUCCESS';
	const FAILURE = 'FAILURE';

	/**
	 * @var Calendar_Model_DbTable_Reservation
	 */
	protected $_dbTable = null;
	
	/**
	 * @return Calendar_Model_DbTable_Reservation
	 */
	public function getDbTable() {
		if (null === $this->_dbTable) {
			$this->_dbTable = new Calendar_Model_DbTable_Reservation();
		}
		return $this->_dbTable;
	}

	/**
	 * @var string
	 */
	private $_status = null;
	
	/**
	 * @return string
	 */
	public function getStatus() {
		$status = $this->_status;
		$this->_status = null;
		return $status;
	}

	/**
	 * @param string $status
	 * @return KontorX_Controller_Action_Helper_Scaffold
	 */
	protected function _setStatus($status) {
		$this->_status = $status;
	}
	
	/**
	 * @param integer $year
	 * @return array
	 */
	public function getFromTo($year) {
		$table = $this->getDbTable();
		$select = $table->select()
			->where('YEAR(`from`) = ?', $year)
			->where('YEAR(`to`) = ?', $year);

		try {
			$rowset = $table->fetchAll($select);
			$this->_setStatus(self::SUCCESS);
			return $rowset->toArray();
		} catch (Zend_Db_Table_Exception $e) {
			$this->_setStatus(self::FAILURE);
		}
	}
	
	/**
	 * @param array $data
	 * @return void
	 */
	public function editableUpdate(array $data) {
		$table = $this->getDbTable();
		$db = $table->getAdapter();

		$parentKey = $table->info(Zend_Db_Table::PRIMARY);
		$whereBase = implode(' = %s AND ', $parentKey) . ' = %s';
		
		$db->beginTransaction();
		try {
			foreach ($data as $key => $values) {
				$key = explode(KontorX_DataGrid_Cell_Editable_Abstract::SEPARATOR, $key);
				$where = vsprintf($whereBase, $key);
				$table->update($values, $where);
			}
			$db->commit();
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Db_Table_Exception $e) {
			$db->rollBack();
			$this->_setStatus(self::FAILURE);
		}
	}
	
	/**
	 * @param array $data
	 * @return void
	 */
	public function editableDelete(array $data) {
		$table = $this->getDbTable();
		$db = $table->getAdapter();

		$parentKey = $table->info(Zend_Db_Table::PRIMARY);
		$whereBase = implode(' = %s AND ', $parentKey) . ' = %s';
		
		$db->beginTransaction();
		try {
			foreach ($data as $key => $values) {
				// większe od zera .. zakładam że autoincrement jest od 1..
				if (isset($values['id']) && $values['id'] > 0) {
					// TODO Nalezy pamiętać o tym że mogą to być rekordy z tree..
					$key = explode(KontorX_DataGrid_Cell_Editable_Abstract::SEPARATOR, $key);
					$where = vsprintf($whereBase, $key);
					$table->delete($where);
				}
			}
			$db->commit();
			$this->_setStatus(self::SUCCESS);
		} catch (Zend_Db_Table_Exception $e) {
			$db->rollBack();
			$this->_setStatus(self::FAILURE);
		}
	}
}